﻿/* The Computer Language Benchmarks Game
 * http://benchmarksgame.alioth.debian.org/
 *
 * Port of the C code that uses GMP
 * Just switched it to use C#'s BigInteger instead
 * 
 * To compile use csc /o+ /r:System.Numerics.dll
 */
using System;
using System.Text;
using System.Runtime.CompilerServices;
using System.Numerics;

public class pidigits
{
    BigInteger acc, den, num;
    public pidigits()
    {
        acc = BigInteger.Zero;
        den = BigInteger.One;
        num = BigInteger.One;
    }
    public uint extract_digit(uint nth)
    {
        return (uint)((num * nth + acc) / den);
    }
    public void eliminate_digit(uint d)
    {
        acc -= den * d;
        acc *= 10;
        num *= 10;
    }
    public void next_term(uint k)
    {
        uint k2 = k * 2 + 1;
        acc += num * 2;
        acc *= k2;
        den *= k2;
        num *= k;
    }
    public void Calculate(int n)
    {
        StringBuilder sb = new StringBuilder(20);
        uint d, k, i;
        for (i = k = 0; i < n; )
        {
            next_term(++k);
            if (num > acc)
                continue;
            d = extract_digit(3);
            if (d != extract_digit(4))
                continue;
            sb.Append((char)('0' + d));
            if (++i % 10 == 0)
            {
                Console.WriteLine("{0}\t:{1}", sb, i);
                sb.Clear();
            }
            eliminate_digit(d);
        }
    }
    public static void Main(String[] args)
    {
        pidigits p = new pidigits();
        p.Calculate(args.Length == 0 ? 10 : Int32.Parse(args[0]));
    }
}

